package com.tim.helper.project;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;
/**
 * <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId>
 * <version>7.11.0</version> </dependency>
 */
public class QiNiuFileServiceImpl2 {
    private String accessKey="";
    private String secretKey="";
    private String zone0="cn-east-2";//存储区域华东
    private String bucketAvatar="dev-pigshop-avatar";//存储域 公共存储域

    Auth auth;

    BucketManager bucketManager;

    public static void main(String[] args) {
        new QiNiuFileServiceImpl2()
                .fileUrlUpload("https://img-blog.csdnimg.cn/img_convert/f0208627800d66cb09ebe2fbf4ecaf7c.png", "12345rtyuio");

    }

    public void fileUrlUpload(String url, String fileName) {
        BucketManager manager = getUploadManager(zone0);
        FetchRet fetchRet = null;
        try {
            //调用fetch方法抓取文件
            fetchRet = manager.fetch(url, bucketAvatar, fileName);
            String imgUrl = fetchRet != null ? fetchRet.key==null||fetchRet.key.trim().length()==0 ? "" : "getPublicImgUrl" : "";
            System.out.println(imgUrl);
        } catch (QiniuException e) {
            //捕获异常信息
            Response r = e.response;
            e.printStackTrace();
        }
    }

    private BucketManager getUploadManager(String zone) {
        Zone z = getZone(zone);// z 为 null
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(z);
//        Auth auth = Auth.create(accessKey, secretKey);
        if(bucketManager == null){
            bucketManager  = new BucketManager(getInstance(), cfg);
        }
        return this.bucketManager;
    }

    private Auth getInstance() {
        if (null == auth) {
            auth =  Auth.create(accessKey, secretKey);
        }
        return this.auth;
    }


    protected final static String EAST_CHINA = "0";//华东

    protected final static String NORTH_CHINA = "1";//华北

    protected final static String SOUTH_CHINA = "2";//华南

    protected final static String NORTH_AMERICA = "Na0";//北美

    protected final static String SOUTHEAST_ASIA = "As0";//东南亚


    /**
     * @Description: 可以通过该方法获取七牛 区域对象
     * @Param:
     * @return:
     * @Author: CXiaoLin
     * @Date:
     */
    public static Zone getZone(String code) {
        switch (code) {
            case EAST_CHINA:
                return Zone.zone0();
            case NORTH_CHINA:
                return Zone.zone1();
            case SOUTH_CHINA:
                return Zone.zone2();
            case NORTH_AMERICA:
                return Zone.zoneNa0();
            case SOUTHEAST_ASIA:
                return Zone.zoneAs0();
            default:
                return null;
        }
    }
}
